package com.syncomponents.convert;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 消息转换器工具类
 * 
 * @author sunkey
 * @date Jan 14, 2014
 */
@Component
public class MessageConvertContainerImpl implements IMessageConvertContainer, BeanFactoryAware {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private BeanFactory beanFactory;

    private final Map<String, String> converterMap = new HashMap<String, String>();

    @Override
    public void registerMessageConverter(String msgType, IMessageConvert<?> messageConverter) {
        Assert.notNull(msgType, "msgType is required");
        Assert.notNull(messageConverter, "messageConverter is required");
        logger.info("msgType:{}, messageConverter:{}", msgType, messageConverter.getClass().getName());
        converterMap.put(msgType, messageConverter.getBeanName());
    }

    @Override
    public IMessageConvert<?> getMessageConverter(String msgType) {
        Assert.notNull(msgType, "msgType is required");
        return beanFactory.getBean(converterMap.get(msgType), IMessageConvert.class);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

}
